import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:visibility_detector/visibility_detector.dart';

/// 轮训Mixin,减少页面代码.
/// 使用需要 with WidgetsBindingObserver, PollingMixin<FlashSwapPage>,调整轮训时间覆写getPollIntervalSeconds
mixin GTPollingMixin<T extends StatefulWidget> on State<T>, WidgetsBindingObserver {
  Timer? _timer;

  void startPolling() {
    _timer = Timer.periodic(Duration(seconds: getPollIntervalSeconds()), (timer) {
      onPoll(timer.tick);
    });
  }

  void onPoll(int tick);

  void stopPolling() {
    _timer?.cancel();
    _timer = null;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    stopPolling();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      startPolling();
    } else {
      stopPolling();
    }
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: Key('${runtimeType.toString()}-visibility-detector'),
      onVisibilityChanged: (visibilityInfo) {
        if (visibilityInfo.visibleFraction == 1.0) {
          startPolling();
        } else {
          stopPolling();
        }
      },
      child: buildPage(context),
    );
  }

  Widget buildPage(BuildContext context);

  int getPollIntervalSeconds() => 3;
}
